package com.endpoint.home.controller;

import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Project: endpoint
 * @Name: HomeController
 * @Author: Jack_Li
 * @Date: 2024/7/4 18:53
 */

@RestController
@RequestMapping("/home")
public class HomeController {

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/testLock")
    public String testLock() {
        //1、获取同一把锁，只要锁的名字一样，就是同一把锁，
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
        lock.lock(10, TimeUnit.SECONDS);//阻塞式等待
        try{
            System.out.println("加锁成功,执行业务:"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("解锁成功:"+Thread.currentThread().getId());
            lock.unlock();
        }
        return "testLock";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        String str="";
        //获取读写锁对象  读写都是 同一个 key my-rwlock
        RReadWriteLock lock = redisson.getReadWriteLock("my-rwlock");
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            System.out.println("写锁加锁成功。。。。"+Thread.currentThread().getId());
            //模拟获取UUID 写入redis
            str = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("rwtest", str);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();//解锁
        }
        return str;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        String str="";
        //获取读写锁对象  读写都是 同一个 key my-rwlock
        RReadWriteLock lock = redisson.getReadWriteLock("my-rwlock");
        //获取读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功。。。。"+Thread.currentThread().getId());
            str = redisTemplate.opsForValue().get("rwtest");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //解锁
            rLock.unlock();
        }
        return str;
    }

}
